package com.ywk.miaohsa.service;

import com.ywk.miaohsa.domain.MiaoshaOrder;
import com.ywk.miaohsa.domain.MiaoshaUser;
import com.ywk.miaohsa.domain.OrderInfo;
import com.ywk.miaohsa.redis.MiaoshaKey;
import com.ywk.miaohsa.redis.RedisService;
import com.ywk.miaohsa.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class MiaoshaService {

    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderService orderService;

    @Autowired
    RedisService redisService;

    /**
     * 秒杀结果有三种情况
     * >0,秒杀成功
     * =0,排队中，等待秒杀
     * <0,秒杀失败
     * @param userId
     * @param goodsId
     * @return
     */
    public long getMiaoshaResult(long userId) {
        MiaoshaOrder miaoshaOrder = orderService.getMiaoshaOrderByUserIdGoodsId(userId);
        if (miaoshaOrder != null) {
            return miaoshaOrder.getOrderId();
        } else {
            boolean isOver = getGoodsOver(miaoshaOrder.getGoodsId());
            if (isOver) {
                return -1;//库存不足，秒杀失败
            }else {
                return 0;
            }
        }
    }

    @Transactional
    public OrderInfo miaosha(MiaoshaUser user, GoodsVo goods) {
        //减库存，下订单，写入秒杀
        boolean success=goodsService.reduceStock(goods);
        if (success) {//减库存成功
            return orderService.createOrder(user,goods);
        }else {//减库存失败，库存不足
            setGoodsOver(goods.getId());
            return null;
        }
    }

    
    
    private void setGoodsOver(long goodsId) {
        redisService.set(MiaoshaKey.isGoodsOver, ""+goodsId, true);
    }


    private boolean getGoodsOver(long goodsId) {
        return redisService.exists(MiaoshaKey.isGoodsOver,""+goodsId);
    }
}
